from sqlalchemy import String, ForeignKey, UniqueConstraint
from sqlalchemy.orm import mapped_column, Mapped, relationship

from models import BaseTable


class DeviceTable(BaseTable):
    __tablename__ = "device"

    no: Mapped[str] = mapped_column(String(32), unique=True, comment="设备编号")
    name: Mapped[str] = mapped_column(String(32), comment="设备名称")
    disabled: Mapped[bool] = mapped_column(default=False, comment="设备是否禁用")
    remark: Mapped[str] = mapped_column(nullable=True, comment="备注信息")

    netInterfaceId: Mapped[int] = mapped_column(ForeignKey("net_interface.id"))
    communicationId: Mapped[str] = mapped_column(String(32), nullable=True, comment="通讯协议代号")

    points: Mapped[list["PLCPointTable"]] = relationship("PLCPointTable", viewonly=True)
    netInterface: Mapped["NetInterfaceTable"] = relationship("NetInterfaceTable")
    scripts: Mapped[list["ScriptTable"]] = relationship("ScriptTable", secondary="r_script_device", viewonly=True)


class NetInterfaceTable(BaseTable):
    __tablename__ = "net_interface"

    host: Mapped[str] = mapped_column(String(255), comment="ip地址")
    port: Mapped[int] = mapped_column(comment="端口号")


class PLCPointTable(BaseTable):
    __tablename__ = "plc_point"

    name: Mapped[str] = mapped_column(String(32), comment="点位名称")
    func: Mapped[str] = mapped_column(String(8), comment="点位功能码")
    addr: Mapped[int] = mapped_column(comment="点位地址")
    desc: Mapped[str] = mapped_column(String(255), nullable=True, comment="点位描述")
    group: Mapped[str] = mapped_column(String(255), nullable=True, comment="点位所属组名")
    deviceNo: Mapped[str] = mapped_column(ForeignKey("device.no", ondelete="CASCADE"))

    __table_args__ = (UniqueConstraint("name", "group", "deviceNo"),)
